const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const archiver = require('archiver');
const extract = require('extract-zip');
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');

const app = express();
const port = process.env.PORT || 3000;

// 设置静态文件目录
app.use(express.static(path.join(__dirname)));

// 设置文件上传存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, 'uploads');
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        cb(null, `${uuidv4()}-${file.originalname}`);
    }
});

const upload = multer({ 
    storage: storage,
    limits: { fileSize: 100 * 1024 * 1024 } // 限制文件大小为100MB
});

// 创建临时目录
const tempDir = path.join(__dirname, 'temp');
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
}

// 定期清理临时文件
setInterval(() => {
    const now = Date.now();
    fs.readdir(tempDir, (err, files) => {
        if (err) return;
        files.forEach(file => {
            const filePath = path.join(tempDir, file);
            fs.stat(filePath, (err, stats) => {
                if (err) return;
                // 删除超过1小时的临时文件
                if (now - stats.mtime.getTime() > 60 * 60 * 1000) {
                    fs.unlink(filePath, () => {});
                }
            });
        });
    });
}, 30 * 60 * 1000); // 每30分钟检查一次

// 图片压缩API
app.post('/api/image/compress', upload.single('image'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: '没有上传文件' });
        }

        const quality = parseInt(req.body.quality) || 80;
        const outputPath = path.join(tempDir, `compressed-${uuidv4()}.jpg`);
        
        await sharp(req.file.path)
            .jpeg({ quality })
            .toFile(outputPath);
            
        res.json({
            success: true,
            file: path.basename(outputPath)
        });
        
        // 删除原始上传文件
        fs.unlink(req.file.path, () => {});
    } catch (error) {
        console.error('图片压缩错误:', error);
        res.status(500).json({ error: '图片压缩失败' });
    }
});

// 图片格式转换API
app.post('/api/image/convert', upload.single('image'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: '没有上传文件' });
        }

        const format = req.body.format || 'jpeg';
        const quality = parseInt(req.body.quality) || 80;
        const outputPath = path.join(tempDir, `converted-${uuidv4()}.${format}`);
        
        let sharpInstance = sharp(req.file.path);
        
        switch (format) {
            case 'jpeg':
            case 'jpg':
                sharpInstance = sharpInstance.jpeg({ quality });
                break;
            case 'png':
                sharpInstance = sharpInstance.png({ quality: quality / 10 });
                break;
            case 'webp':
                sharpInstance = sharpInstance.webp({ quality });
                break;
            case 'gif':
                sharpInstance = sharpInstance.gif();
                break;
            default:
                return res.status(400).json({ error: '不支持的格式' });
        }
        
        await sharpInstance.toFile(outputPath);
            
        res.json({
            success: true,
            file: path.basename(outputPath)
        });
        
        // 删除原始上传文件
        fs.unlink(req.file.path, () => {});
    } catch (error) {
        console.error('图片转换错误:', error);
        res.status(500).json({ error: '图片转换失败' });
    }
});

// 图片水印API
app.post('/api/image/watermark', upload.fields([
    { name: 'image', maxCount: 1 },
    { name: 'watermarkImage', maxCount: 1 }
]), async (req, res) => {
    try {
        if (!req.files || !req.files.image) {
            return res.status(400).json({ error: '没有上传图片' });
        }

        const image = req.files.image[0];
        const outputPath = path.join(tempDir, `watermarked-${uuidv4()}.png`);
        
        let sharpInstance = sharp(image.path);
        
        // 文字水印
        if (req.body.watermarkType === 'text' && req.body.text) {
            const svgBuffer = Buffer.from(`
                <svg width="500" height="100">
                    <text x="50%" y="50%" font-family="Arial" font-size="${req.body.fontSize || 24}" 
                          fill="rgba(${req.body.color || '255,255,255,0.5'})" text-anchor="middle" dominant-baseline="middle">
                        ${req.body.text}
                    </text>
                </svg>
            `);
            
            const { width, height } = await sharpInstance.metadata();
            
            await sharpInstance
                .composite([{
                    input: svgBuffer,
                    gravity: req.body.position || 'southeast'
                }])
                .toFile(outputPath);
        }
        // 图片水印
        else if (req.body.watermarkType === 'image' && req.files.watermarkImage) {
            const watermarkImage = req.files.watermarkImage[0];
            const opacity = parseFloat(req.body.opacity) || 0.5;
            
            await sharpInstance
                .composite([{
                    input: watermarkImage.path,
                    gravity: req.body.position || 'southeast',
                    blend: 'over'
                }])
                .toFile(outputPath);
                
            // 删除水印图片
            fs.unlink(watermarkImage.path, () => {});
        } else {
            return res.status(400).json({ error: '无效的水印设置' });
        }
            
        res.json({
            success: true,
            file: path.basename(outputPath)
        });
        
        // 删除原始上传文件
        fs.unlink(image.path, () => {});
    } catch (error) {
        console.error('水印添加错误:', error);
        res.status(500).json({ error: '水印添加失败' });
    }
});

// 文件压缩API
app.post('/api/file/compress', upload.array('files'), (req, res) => {
    try {
        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ error: '没有上传文件' });
        }

        const outputPath = path.join(tempDir, `archive-${uuidv4()}.zip`);
        const output = fs.createWriteStream(outputPath);
        const archive = archiver('zip', {
            zlib: { level: parseInt(req.body.level) || 9 }
        });
        
        output.on('close', function() {
            res.json({
                success: true,
                file: path.basename(outputPath),
                size: archive.pointer()
            });
            
            // 删除原始上传文件
            req.files.forEach(file => {
                fs.unlink(file.path, () => {});
            });
        });
        
        archive.on('error', function(err) {
            console.error('压缩错误:', err);
            res.status(500).json({ error: '文件压缩失败' });
        });
        
        archive.pipe(output);
        
        // 添加文件到压缩包
        req.files.forEach(file => {
            archive.file(file.path, { name: file.originalname });
        });
        
        archive.finalize();
    } catch (error) {
        console.error('文件压缩错误:', error);
        res.status(500).json({ error: '文件压缩失败' });
    }
});

// 文件解压API
app.post('/api/file/extract', upload.single('archive'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: '没有上传文件' });
        }

        const extractDir = path.join(tempDir, `extract-${uuidv4()}`);
        fs.mkdirSync(extractDir, { recursive: true });
        
        await extract(req.file.path, { dir: extractDir });
        
        // 获取解压后的文件列表
        const fileList = [];
        const walkDir = (dir, baseDir = '') => {
            const files = fs.readdirSync(dir);
            files.forEach(file => {
                const filePath = path.join(dir, file);
                const relativePath = path.join(baseDir, file);
                const stat = fs.statSync(filePath);
                if (stat.isDirectory()) {
                    walkDir(filePath, relativePath);
                } else {
                    fileList.push({
                        name: file,
                        path: relativePath,
                        size: stat.size
                    });
                }
            });
        };
        
        walkDir(extractDir);
        
        res.json({
            success: true,
            directory: path.basename(extractDir),
            files: fileList
        });
        
        // 删除原始上传文件
        fs.unlink(req.file.path, () => {});
    } catch (error) {
        console.error('文件解压错误:', error);
        res.status(500).json({ error: '文件解压失败' });
    }
});

// 下载处理后的文件
app.get('/download/:filename', (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join(tempDir, filename);
    
    if (fs.existsSync(filePath)) {
        res.download(filePath);
    } else {
        res.status(404).send('文件不存在');
    }
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
}); 